package com.itealabs.postjson.ext;

import com.itealabs.postjson.JsonCallWaiter;
import com.itealabs.postjson.JsonCallWaiterLocator;

/**
 * Load JsonCallWaiters according to qualified class name.
 * 
 * @version $Id: JsonCallWaiterClasspathLocator.java 14 2010-04-23 09:33:42Z iteahere $
 * @author itea 2010-4-18
 */
public class JsonCallWaiterClasspathLocator implements JsonCallWaiterLocator {

	private boolean supportPojo = false;
	
	static Object getInstance(String clzName) {
		try {
			Class<?> clz = Thread.currentThread().getContextClassLoader()
					.loadClass(clzName);
			return clz.newInstance();
		} catch (Exception e) {
			return null;
		}
	}

	public JsonCallWaiter getCallWaiter(String method) {
		
		Object obj = getInstance(method);
		if(obj == null)
			obj = getInstance(method.replaceAll("\\.[\\w\\d_]*$", ""));
		if(obj == null) return null;
		if (obj instanceof JsonCallWaiter)
			return (JsonCallWaiter) obj;
		else if (supportPojo)
			return new ReflectionJsonCallWaiter(obj);
		else
			return null;
	}

	public boolean isSupportPojo() {
		return supportPojo;
	}

	public void setSupportPojo(boolean supportPojo) {
		this.supportPojo = supportPojo;
	}

}
